package com.liao.badminton.server;

import com.liao.badminton.handler.ServerChannelMyselfInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

//@Component
public class StartNettyServer implements ApplicationRunner {
    Logger logger = LoggerFactory.getLogger(StartNettyServer.class);

    public static Integer port = 12222;

    @Value("${netty.port}")
    public void setPort(Integer port) {
        StartNettyServer.port = port;
    }

    @Override
    public void run(ApplicationArguments args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
//                .childHandler(new ServerChannelObjectInitializer())
                .childHandler(new ServerChannelMyselfInitializer()) //自定义编解码
                .localAddress(port)
                //设置队列大小
                .option(ChannelOption.SO_BACKLOG, 1024)
                // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        //绑定端口,开始接收进来的连接
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            logger.info("服务器启动开始监听端口: {}", port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭主线程组
            bossGroup.shutdownGracefully();
            //关闭工作线程组
            workGroup.shutdownGracefully();
        }
    }
}
